package demo3;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class MyTimer {
    private BlockingQueue<MyTask> queue=new PriorityBlockingQueue<>();

    public MyTimer(){
        Thread thread =new Thread(()->{
            while (true){
                try {
                    MyTask myTask=queue.take();
                    if(System.currentTimeMillis()>=myTask.getTime()){
                        myTask.getRunnable().run();
                    }else{
                        queue.put(myTask);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }
    public void schedule(Runnable runnable,long delay) throws InterruptedException {
        queue.put(new MyTask(runnable,delay));
    }
}
class  MyTask implements Comparable<MyTask>{
    private Runnable runnable;
    private long time;

    public MyTask(Runnable runnable, long delay) {
        if(runnable==null) throw new IllegalArgumentException("任务不能为空");
        if(delay<0) throw new IllegalArgumentException("时间不能为空");
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+delay;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        if(this.getTime()>o.getTime()) return 1;
        else if(this.getTime()<o.getTime()) return -1;
        else return 0;
    }
}
